//
//  JSHorizontalLayoutView.m
//  JSBasicFramework
//
//  Created by Apple on 2018/8/31.
//  Copyright © 2018年 Apple. All rights reserved.
//

#import "JSHorizontalLayoutView.h"

@implementation JSHorizontalLayoutView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self didInitialized];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self didInitialized];
    }
    return self;
}
-(void)didInitialized{
    _padding = UIEdgeInsetsMake(5, 5, 5, 5);
    _itemMargins = _padding;
    _contenScrollView = [[UIScrollView alloc] init];
    [self addSubview:_contenScrollView];
//    [_contenScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.equalTo(self);
//    }];
}
- (CGSize)sizeThatFits:(CGSize)size {
    return [self layoutSubviewsWithSize:size shouldLayout:NO];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [self layoutSubviewsWithSize:self.bounds.size shouldLayout:YES];
    self.contenScrollView.frame = CGRectMake(self.padding.left, self.padding.top, self.width - self.padding.left - self.padding.right, self.height - self.padding.top - self.padding.bottom);
   
}

- (CGSize)layoutSubviewsWithSize:(CGSize)size shouldLayout:(BOOL)shouldLayout {
    NSArray<UIView *> *visibleItemViews = [self visibleSubviews];
    if (visibleItemViews.count == 0) {
        return CGSizeMake(UIEdgeInsetsGetHorizontalValue(self.padding), UIEdgeInsetsGetVerticalValue(self.padding));
    }
    CGFloat h = 0;
    CGFloat contentW = 0;
    for (NSInteger i = 0; i < visibleItemViews.count; i ++) {
        UIView *item = visibleItemViews[i];
        
        CGSize itemSize = [item sizeThatFits:CGSizeMake(item.width, item.height)];
        if (!h) { // UIEdgeInsetsGetVerticalValue(self.padding) +
            h +=  itemSize.height;
        }
        if (itemSize.height > self.height - self.padding.top - self.padding.bottom) {
            itemSize = CGSizeMake(self.height - self.padding.top - self.padding.bottom, self.height - self.padding.top - self.padding.bottom);
        }
        item.frame = CGRectMake(contentW, 0, itemSize.width, itemSize.height);
        contentW = item.right + UIEdgeInsetsGetHorizontalValue(self.itemMargins);
    }
    self.contenScrollView.contentSize = CGSizeMake(contentW, h);
    return CGSizeMake(size.width, h);
}

- (NSArray<UIView *> *)visibleSubviews {
    NSMutableArray<UIView *> *visibleItemViews = [[NSMutableArray alloc] init];
    
    for (NSInteger i = 0, l = self.contenScrollView.subviews.count; i < l; i++) {
        UIView *itemView = self.contenScrollView.subviews[i];
        if (!itemView.hidden) {
            [visibleItemViews addObject:itemView];
        }
    }
    
    return visibleItemViews;
}
@end
